package cn.dlc.com.config;

import cn.dlc.com.interceptor.MyAuthenticateInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

/**
 * @author 邓立川
 * @date 2021/11/21 10:02
 * @desc springmvc的核心配置
 */
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "cn.dlc.com",
        // 单纯扫描controller和RestController
        includeFilters = {
                @ComponentScan.Filter(type = FilterType.ANNOTATION,value = RestController.class),
                @ComponentScan.Filter(type = FilterType.ANNOTATION, value = Controller.class)} )
public class SpringMvcConfig implements WebMvcConfigurer {

    // 视图解析器
    @Bean
    public InternalResourceViewResolver viewResolver(){
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/view/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }

    /**
     * 指定映射
     * @param registry
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        // 访问根目录的时候，跳转到login这个视图
        // 这样就不需要额外写一个controller来跳转了
        registry.addViewController("/").setViewName("login");
        /*// 如果访问的是test，那么直接重定向到user/r1这个地址，而不是视图（两种不同的配置方式）
        registry.addRedirectViewController("/test","/user/r1");
        // 上面两种是等价的
        registry.addViewController("/test").setViewName("redirect:/user/r1");*/
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

//        String[] whiteUrl = new String[]{"/user/login","/user/logout","/"};
        String[] whiteUrl = new String[]{};
        // 这个地方的路径是从ip后开始截取的，所以如果有网站名要加上，否则不会过滤
        // 下面是会拦截http://localhost:port/user/r/**等路径
        // 如果网站名是springmvc，那么路径是http://localhost:port/springmvc/user/r/**
        // 不会被拦截
        registry.addInterceptor(new MyAuthenticateInterceptor()).
                excludePathPatterns(whiteUrl).
                addPathPatterns("/user/r/**");
    }
}
